package com.tanfuqi.sicent.server.controller

import com.tanfuqi.sicent.protocol.message.Message
import com.tanfuqi.sicent.protocol.message.Online
import com.tanfuqi.sicent.protocol.message.QueryBody
import com.tanfuqi.sicent.protocol.message.Switch
import com.tanfuqi.sicent.server.filter.sent
import io.swagger.annotations.ApiOperation
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.*
import reactor.core.publisher.Mono
import reactor.core.publisher.toMono

@RestController
class OnlineController : BaseController() {
    @ApiOperation(value = "上机会员查询")
    @GetMapping(value = ["/shop/{shopId}/member/online/{value}/type/{type}"])
    fun online(@PathVariable shopId: String, @PathVariable value: String,
               @PathVariable type: Int): Mono<Any> =
            session(shopId).sent(Message(0x8005, body = QueryBody(value, type))).map { it.body }

    @ApiOperation(value = "会员上机")
    @PostMapping(value = ["/shop/{shopId}/member/online/{cardId}"])
    @ResponseStatus(HttpStatus.CREATED)
    fun online(@PathVariable shopId: String, @PathVariable cardId: String, @RequestBody online: Online): Mono<Any> =
            cardId.toMono().map {
                online.cardId = cardId
                online
            }.flatMap { online ->
                session(shopId).sent(Message(0x8046, body = online)).map { it.body }

            }

        @ApiOperation(value = "会员下机")
    @DeleteMapping(value = ["/shop/{shopId}/member/online/{cardId}"])
    fun offline(@PathVariable shopId: String, @PathVariable cardId: String): Mono<Any> =
                session(shopId).sent(Message(0x8005, body = Online(cardId))).map { it.body }


    @ApiOperation(value = "会员换机")
    @PatchMapping(value = ["/shop/{shopId}/member/online/{cardId}/from/{fromComputer}/to/{toComputer}"])
    fun swich(@PathVariable shopId: String, @PathVariable cardId: String,
              @PathVariable fromComputer: String, @PathVariable toComputer: String): Mono<Any> =
            cardId.toMono().map { cardId -> Message(if (cardId.startsWith("-")) 0x8066 else 0x8049, body = Switch(cardId, fromComputer, toComputer)) }
                    .flatMap { message ->
                        session(shopId).sent(message).map { it.body }
                    }


}